import koaRequest from 'koa2-request';
import fs from 'fs';
import path from 'path';
const __dirname = path.resolve();

//   金价查询
const getGoldList = async (ctx, next) => {
  let res = await koaRequest({
    url: 'https://api.lolimi.cn/API/huangj/api.php',
    method: 'get'
  });
  ctx.success(JSON.parse(res.body), 'success');
};

// fb / x 分享跳转
const shareLinkTemplate = async (ctx, next) => {
  if (!ctx.query.v) {
    ctx.fail('1009', '参数为空');
  } else {
    const tdk = ctx.query.v ? ctx.query.v.split(',') : [];
    const filePath = path.join(__dirname, 'utils/template/shareIndex.html');
    let html = fs.readFileSync(filePath, 'utf8');
    html = html.replace(
      /@@title@@|@@desc@@|@@img@@|@@link@@|@@imgh@@|@@imgw@@/gi,
      function (matchStr) {
        const tokenMap = {
          '@@title@@': tdk[0] || '',
          '@@desc@@': tdk[1] || '',
          '@@img@@': tdk[2] || '',
          '@@link@@': tdk[3] || '',
          '@@imgh@@': tdk[4] || '628',
          '@@imgw@@': tdk[5] || '1200'
        };
        return tokenMap[matchStr];
      }
    );
    ctx.type = 'html';
    ctx.body = html;
  }
};

export default {
  'GET&/utils/goldList': getGoldList,
  'GET&/utils/shareLink': shareLinkTemplate
};
